<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow;
          header_list[e].value = header_list[e].type == 'input_number' ? ['', ''] : '';
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = item.type == 'input_number' ? ['', ''] : '';
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div>奖罚列表</div>
        <div class="flex">
          <el-button type="primary" @click="show_box = true">新增</el-button>
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable;
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true;
                });
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e;
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height: height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column type="index" label="序号" width="80px"></el-table-column>
        <el-table-column
          label="项目名称"
          prop="projectName"
          key="项目名称"
          sortable
          v-if="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          label="标题"
          prop="title"
          key="标题"
          sortable
          show-overflow-tooltip
          v-if="header_list[1].showTable"
        ></el-table-column>
        <el-table-column label="类型" key="类型" sortable v-if="header_list[2].showTable">
          <template #default="scope">
            <div v-if="scope.row.type == 1">奖励</div>
            <div v-else>处罚</div>
          </template>
        </el-table-column>
        <el-table-column
          label="相关成员"
          prop="memberName"
          key="相关成员"
          sortable
          v-if="header_list[3].showTable"
        ></el-table-column>
        <el-table-column
          label="相关角色"
          key="相关角色"
          sortable
          v-if="header_list[4].showTable"
        >
          <template #default="scope">
            <div v-if="scope.row.roleType == 1">设计成员</div>
            <div v-if="scope.row.roleType == 2">设计经理</div>
            <div v-if="scope.row.roleType == 3">设计组长</div>
          </template>
        </el-table-column>
        <el-table-column
          width="60"
          label="面积"
          prop="area"
          key="面积"
          sortable
          v-if="header_list[5].showTable"
        ></el-table-column>
        <el-table-column
          width="60"
          label="单价"
          prop="price"
          key="单价"
          sortable
          v-if="header_list[6].showTable"
        ></el-table-column>
        <el-table-column
          label="金额类型"
          key="金额类型"
          sortable
          v-if="header_list[7].showTable"
        >
          <template #default="scope">
            <div v-if="scope.row.amountType == 1">固定金额</div>
            <div v-else>金额占比</div>
          </template> </el-table-column
        ><el-table-column
          label="比例"
          key="比例"
          sortable
          v-if="header_list[8].showTable"
        >
          <template #default="scope">
            <div v-if="scope.row.amountType != 1">
              {{ scope.row.proportion }}
            </div>
          </template> </el-table-column
        ><el-table-column
          label="金额"
          prop="amount"
          key="金额"
          sortable
          v-if="header_list[9].showTable"
        >
        </el-table-column
        ><el-table-column
          label="实际金额"
          prop="actualAmount"
          key="实际金额"
          sortable
          v-if="header_list[10].showTable"
        ></el-table-column
        ><el-table-column
          label="创建时间"
          prop="createTime"
          key="创建时间"
          sortable
          v-if="header_list[11].showTable"
          ><template #default="scope">
            <div v-if="scope.row.createTime ?? '' !== ''">
              {{ formatDate(parseInt(scope.row.createTime), "YYYY-MM-DD") }}
            </div>
            <div v-else>-- --</div>
          </template></el-table-column
        ><el-table-column
          label="创建人"
          prop="createByName"
          key="创建人"
          sortable
          v-if="header_list[12].showTable"
        ></el-table-column
        ><el-table-column
          label="原因"
          prop="remark"
          key="比例"
          sortable
          show-overflow-tooltip
          v-if="header_list[13].showTable"
        ></el-table-column>
        <el-table-column
          label="处理状态"
          key="处理状态"
          sortable
          prop="isDelete"
          v-if="header_list[14].showTable"
        >
          <template #default="scope">
            <div v-if="scope.row.verificationStatus">已核销</div>
            <div v-else>未核销</div>
          </template></el-table-column
        >
        <el-table-column
          width="120"
          label="处理时间"
          prop="code"
          key="处理时间"
          sortable
          v-if="header_list[15].showTable"
          ><template #default="scope">
            <div v-if="scope.row.verificationTime ?? '' !== ''">
              {{ formatDate(parseInt(scope.row.verificationTime), "YYYY-MM-DD") }}
            </div>
            <div v-else>-- --</div>
          </template></el-table-column
        >
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope: any">
            <el-button
              @click="edit_list({ item: scope.row, type: 1 })"
              v-if="!scope.row.verificationStatus"
              >编辑</el-button
            >
            <el-button
              @click="edit_list({ item: scope.row, type: 2 })"
              v-if="!scope.row.verificationStatus"
              >删除</el-button
            >
            <el-button @click="edit_list({ item: scope.row, type: 3 })">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="50%"
      destroy-on-close
      :close-on-click-modal="false"
      @close="resetForm(addRewardform)"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增奖罚</h4>
        <h4 v-else>
          <span v-if="!add_form_data.verificationStatus">编辑奖罚</span
          ><span v-else>奖罚详情</span>
        </h4>
      </template>
      <template #default>
        <el-form
          ref="addRewardform"
          :model="add_form_data"
          :rules="rules"
          label-width="120"
        >
          <el-form-item label="标题" prop="title">
            <el-input
              :disabled="add_form_data.verificationStatus"
              v-model="add_form_data.title"
              show-word-limit
              maxlength="30"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="项目" prop="taskId">
            <el-select
              v-model="add_form_data.taskId"
              @change="select_taskId"
              :disabled="add_form_data.verificationStatus"
            >
              <el-option
                v-for="item in project_list"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型">
            <el-radio-group
              v-model="add_form_data.type"
              :disabled="add_form_data.verificationStatus"
            >
              <el-radio :label="1">奖励</el-radio>
              <el-radio :label="2">惩罚</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="相关成员">
            <el-radio-group
              v-model="add_form_data.involvedType"
              :disabled="add_form_data.verificationStatus"
            >
              <el-radio :label="1">全体成员</el-radio>
              <el-radio :label="2">单一成员</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="相关角色" v-if="add_form_data.involvedType == 2">
            <el-select
              v-model="add_form_data.roleType"
              :disabled="add_form_data.verificationStatus"
            >
              <el-option label="设计成员" :value="1"></el-option>
              <el-option label="设计经理" :value="2"></el-option>
              <el-option label="设计组长" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            prop="memberId"
            label="成员"
            v-if="add_form_data.roleType == 1 && add_form_data.involvedType == 2"
          >
            <el-select
              v-model="add_form_data.memberId"
              :disabled="add_form_data.verificationStatus"
            >
              <el-option
                v-for="item in dept_member_list"
                :value="item.memberId"
                :key="item.memberId"
                :label="item.memberName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="金额类型">
            <el-radio-group
              v-model="add_form_data.amountType"
              :disabled="add_form_data.verificationStatus"
            >
              <el-radio :label="1">固定金额</el-radio>
              <el-radio :label="2">金额占比</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="比例"
            v-if="add_form_data.amountType == 2"
            prop="proportion"
          >
            <el-input
              :disabled="add_form_data.verificationStatus"
              v-model="add_form_data.proportion"
              type="number"
              show-word-limit
              maxlength="10"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="金额" v-else prop="amount">
            <el-input
              :disabled="add_form_data.verificationStatus"
              v-model="add_form_data.amount"
              type="number"
              show-word-limit
              maxlength="10"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="金额详情" v-if="add_form_data.verificationStatus">
            <el-table :data="amount_detail" border class="tc" max-height="500">
              <el-table-column label="序号" type="index"></el-table-column>
              <el-table-column label="成员" prop="memberName"></el-table-column>
              <el-table-column label="任务" prop="assignTaskName"></el-table-column>
              <el-table-column label="分配权重" prop="assignWeight"></el-table-column>
              <el-table-column label="金额" prop="actualAmount"></el-table-column>
              <el-table-column label="类型">
                <template #default="scope">
                  <div v-if="scope.row.type == 4">奖励</div>
                  <div v-else>处罚</div>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker
              :disabled="add_form_data.verificationStatus"
              :clearable="false"
              v-model="add_form_data.occurTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="x"
              placeholder="请选择"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="原因">
            <el-input
              :disabled="add_form_data.verificationStatus"
              v-model="add_form_data.remark"
              type="textarea"
              show-word-limit
              maxlength="300"
            >
            </el-input>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(addRewardform)">取消</el-button>
            <el-button
              type="primary"
              v-if="!add_form_data.verificationStatus"
              @click="submit(addRewardform)"
              :loading="btn_loading"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, formatDate, debounce, handle_search_key } from "@/utils/check_role"; // 权限校验
import search from "@/view/components/search.vue";
import setTable from "@/view/components/setTable.vue";
import { onMounted, ref, onUnmounted } from "vue";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { useStore } from "vuex";
const store = useStore();
const addRewardform = ref<FormInstance>();
const rules = ref({
  // 表单验证规则
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  taskId: [{ required: true, message: "请选择项目", trigger: "change" }],
  memberId: [{ required: true, message: "请选择成员", trigger: "change" }],
  proportion: [{ required: true, message: "请输入比例", trigger: "blur" }],
  amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
});
const list = ref();
const total = ref();
const max_height = ref();
const loading = ref(false);
const show_box = ref(false);
const height_size = ref(1);
const header_list = ref<any>([
  {
    label: "项目名称",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "标题",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "类型",
    value: "",
    showTable: true,
    type: "select",
    isShow: false,
    options: [
      {
        value: 1,
        label: "奖励",
      },
      {
        value: 2,
        label: "处罚",
      },
    ],
  },
  {
    label: "相关成员",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "相关角色",
    value: "",
    showTable: true,
    type: "select",
    isShow: false,
    options: [
      {
        value: 1,
        label: "设计成员",
      },
      {
        value: 2,
        label: "设计经理",
      },
      {
        value: 3,
        label: "设计组长",
      },
    ],
  },
  {
    label: "面积",
    value: ["", ""],
    showTable: true,
    type: "input_number",
    isShow: false,
    options: [],
  },
  {
    label: "单价",
    value: ["", ""],
    showTable: true,
    type: "input_number",
    isShow: false,
    options: [],
  },
  {
    label: "金额类型",
    value: "",
    showTable: true,
    type: "select",
    isShow: false,
    options: [
      {
        value: 1,
        label: "固定金额",
      },
      {
        value: 2,
        label: "金额占比",
      },
    ],
  },
  {
    label: "比例",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "金额",
    value: ["", ""],
    showTable: true,
    type: "input_number",
    isShow: false,
    options: [],
  },
  {
    label: "实际金额",
    value: ["", ""],
    showTable: true,
    type: "input_number",
    isShow: false,
    options: [],
  },
  {
    label: "创建时间",
    value: "",
    showTable: true,
    type: "date",
    isShow: false,
    options: [],
  },
  {
    label: "创建人",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "原因",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "处理状态",
    value: "",
    showTable: true,
    type: "select",
    isShow: false,
    options: [
      {
        value: true,
        label: "已核销",
      },
      {
        value: false,
        label: "未核销",
      },
    ],
  },
  {
    label: "处理时间",
    value: "",
    showTable: true,
    type: "date",
    isShow: false,
    options: [],
  },
]);
const page_data = ref({
  current: 1,
  pageSize: 10,
  enterpriseId: store.state.enterprise_id,
  projectName: "",
  title: "",
  type: "",
  //   involvedType: "",
  memberName: "",
  roleType: "",
  area: "",
  price: "",
  //   assignWeight: "",
  proportion: "",
  amountType: "",
  amount: "",
  actualAmount: "",

  createTime: "",
  createByName: "",
  remark: "",
  verificationStatus: "",
  verificationTime: "",
});
const add_form_data = ref({
  id: "",
  title: "",
  taskId: "",
  type: 1,
  involvedType: 1,
  roleType: 1,
  memberId: "",
  amountType: 1,
  proportion: "",
  amount: "",
  occurTime: Date.parse(new Date() + ""),
  remark: "",
  verificationStatus: false,
});
onMounted(() => {
  max_height.value = window.innerHeight - 320; // 带分页的 table 高度
  EventBus.on("refresh", () => {
    get_list();
    ElMessage.success("刷新成功！");
  });
  setTimeout(() => {
    get_list();
    get_myProjectTaskList();
  }, 100);
});
const project_list = ref([]); // 项目列表
const get_myProjectTaskList = () => {
  axios
    .request({
      url: serviceApi.tesk_list,
      method: "post",
      data: { current: 1, pageSize: 1000 },
    })
    .then((res) => {
      console.log(res);
      project_list.value = res.data.content.filter((i) => {
        return i.planHours !== null && i.planHours != "";
      });
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
onUnmounted(() => {
  EventBus.off("refresh");
});
const edit_list = (e) => {
  console.log(e);
  if (e.type == 2) {
    ElMessageBox.confirm("确定删除该记录？", "", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      type: "warning",
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.taskRewardDeduction + "/" + e.item.id,
            method: "delete",
          })
          .then((res) => {
            console.log(res);
            ElMessage.success("操作成功！");
            setTimeout(() => {
              get_list();
            }, 1000);
          })
          .catch((err) => {
            ElMessage.error(err);
          });
      })
      .catch(() => {});
  } else {
    add_form_data.value = {
      id: e.item.id,
      title: e.item.title,
      taskId: e.item.taskId,
      type: e.item.type,
      involvedType: e.item.involvedType,
      roleType: e.item.roleType,
      memberId: e.item.memberId,
      amountType: e.item.amountType,
      proportion: e.item.proportion,
      amount: e.item.amount,
      occurTime:
        e.item.occurTime === null
          ? Date.parse(new Date() + "")
          : parseInt(e.item.occurTime),
      remark: e.item.remark,
      verificationStatus: e.type == 3 ? true : e.item.verificationStatus,
    };
    get_list_info(e.item.id);
    select_taskId(e.item.taskId);
    show_box.value = true;
  }
};
const amount_detail = ref([]);
const get_list_info = (e) => {
  axios
    .request({
      url: serviceApi.taskRewardDeduction + "/distributionDetail/" + e,
      method: "get",
    })
    .then((res) => {
      console.log(res);
      amount_detail.value = res.data;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const btn_loading = ref(false);
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return;
      btn_loading.value = true;
      axios
        .request({
          url:
            serviceApi.taskRewardDeduction +
            (add_form_data.value.id == "" ? "" : "/" + add_form_data.value.id),
          method: add_form_data.value.id == "" ? "post" : "put",
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res);
          ElMessage.success("操作成功！");
          setTimeout(() => {
            get_list();
            resetForm(formEl);
            btn_loading.value = false;
          }, 1000);
        })
        .catch((err) => {
          ElMessage.error(err);
          btn_loading.value = false;
        });
    }
  });
};
const dept_member_list = ref(); // 选择项目 => 部门成员列表
const select_taskId = (e) => {
  let deptId = "";
  project_list.value.some((i) => {
    if (i.id == e) {
      deptId = i.deptId;
    }
    return i.id == e;
  });
  axios
    .request({
      url: serviceApi.depart_user_list,
      method: "post",
      params: { deptId: deptId },
    })
    .then((res) => {
      console.log(res);
      dept_member_list.value = res.data == null ? [] : res.data;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const get_list = () => {
  loading.value = true;
  axios
    .request({
      url: serviceApi.taskRewardDeduction + "/page",
      method: "post",
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res);
      list.value = res.data.content;
      total.value = parseInt(res.data.totalElements);
      loading.value = false;
    })
    .catch((err) => {
      ElMessage.error(err);
      loading.value = false;
    });
};
let list_debounce = debounce(200, get_list);
const search_key = () => {
  page_data.value = {
    current: 1,
    pageSize: 10,
    enterpriseId: store.state.enterprise_id,
    projectName: header_list.value[0].value,
    title: header_list.value[1].value,
    type: header_list.value[2].value,
    memberName: header_list.value[3].value,
    //   involvedType: header_list.value[4].value,
    roleType: header_list.value[4].value,
    area: header_list.value[5].value,
    price: header_list.value[6].value,
    // assignWeight: header_list.value[7].value,
    amountType: header_list.value[7].value,
    proportion: header_list.value[8].value,
    amount: header_list.value[9].value,
    actualAmount: header_list.value[10].value,

    createTime: header_list.value[11].value,
    createByName: header_list.value[12].value,
    remark: header_list.value[13].value,
    verificationStatus:
      header_list.value[14].value == undefined ? false : header_list.value[14].value,
    verificationTime: header_list.value[15].value,
  };
  get_list();
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  add_form_data.value = {
    id: "",
    title: "",
    taskId: "",
    type: 1,
    involvedType: 1,
    roleType: 1,
    memberId: "",
    amountType: 1,
    proportion: "",
    amount: "",
    remark: "",
    verificationStatus: false,
    occurTime: Date.parse(new Date() + ""),
  };
  show_box.value = false;
};
</script>

<style lang="scss" scoped>
.top_item {
  border: 1px solid #ccc;
  cursor: pointer;
  padding: 5px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  &:hover {
    color: #3580eb;
    border-color: #3580eb;
  }
}
.line {
  background-color: #333;
  width: 1px;
  height: 16px;
  margin: 0 10px;
}
</style>
